<?php

class cms_article_model extends CI_Model {

    protected $_instance = array(
        'table' => 'cms_article',
        'primaryKey' => 'id',
    );
    public $_data = null;
    protected $_indexes = array(
        "INDEX,FOLLOW",
        "INDEX,NOFOLLOW",
        "NOINDEX,FOLLOW",
        "NOINDEX,NOFOLLOW"
    );

    const TYPE_NORMAL = 0;
    const TYPE_IMAGE = 1;
    const TYPE_VIDEO = 2;
    const TYPE_MIXED = 3;

    protected $_status = array(
        0 => "Lưu tạm",
        1 => "Xuất bản",
        2 => "Gỡ bỏ"
    );

    public function get_articles() {
        $query = $this->db->get($this->_instance['table']);
        $list_article = array();
        foreach ($query->result() as $row) {
            $list_article[] = $row;
        }
        $query->free_result();
        return $list_article;
    }

    public function get_collection($start, $limit, $conds = null, $orders = null) {
        $query = 'SELECT ca.id, ca.alias, ca.category_ids, ca.type, ca.title, ca.description, ca.publish_day, ca.created_at, ca.words, ca.status, ca.hot_article, ca.top_home, ca.top_category, ca.user_id, ca.image, sa.username AS author FROM ' . $this->_instance['table'] . ' ca INNER JOIN site_admin sa ON ca.user_id = sa.id';
        if (is_array($conds)) {
            $conds = implode(' AND ', $conds);
        }
        if (!empty($conds)) {
            $query .= ' WHERE ' . $conds;
        }
        if (!empty($orders)) {
            $query .= ' ORDER BY ' . $orders;
        }
        $query .= ' LIMIT ' . $start . ', ' . $limit;
        $query = $this->db->query($query);
        $list_article = array();
        foreach ($query->result() as $row) {
            $list_article[] = $row;
        }
        $query->free_result();
        return $list_article;
    }

    public function add_article($data) {
        $data = $this->auto_render($data);
        $id = false;
        if (empty($data['error'])) {
            $this->db->insert($this->_instance['table'], $data);
        } else {
            throw new Exception($data['error']);
            return false;
        }
        return $id;
    }

    public function update_article($id, $data) {
        $data = $this->auto_render($data);
        $CI = & get_instance();
        $data['user_id'] = $CI->session->userdata('admin_id');
        if (empty($data['error'])) {
            //Update DB
            $this->db->where('id', $id);
            $this->db->update($this->_instance['table'], $data);
            //Update Memcache
            $CI->st_registry->deleteKey('cms/article_by_id/' . $id);
            if (!empty($data['alias'])) {
                $CI->st_registry->deleteKey('cms/article_by_alias/' . $data['alias']);
            }
        } else {
            throw new Exception($data['error']);
            return false;
        }
        return $this;
    }

    public function load_by_id($id, $reload = true) {
        $CI =& get_instance();
        if ($reload) {
            $query = $this->db->get_where($this->_instance['table'], array('id' => $id), 1, 0);
            $this->_data = $query->row();
            $this->_data = $this->auto_render_load($this->_data);
            $CI->st_registry->setKey('cms/article_by_id/' . $id, $this->_data, CACHE_TIMEOUT);
            $query->free_result();
        } else {
            $this->_data = $CI->st_registry->getKey('cms/article_by_id/' . $id);
            if (!$this->_data) {
                return $this->load_by_id($id, true);
            }
        }
        return $this->_data;
    }

    public function load_by_alias($alias, $reload = true) {
        $CI =& get_instance();
        if ($reload) {
            $query = $this->db->get_where($this->_instance['table'], array('alias' => $alias), 1, 0);
            $this->_data = $query->row();
            $this->_data = $this->auto_render_load($this->_data);
            $CI->st_registry->setKey('cms/article_by_alias/' . $alias, $this->_data, CACHE_TIMEOUT);
            $query->free_result();
        } else {
            $this->_data = $CI->st_registry->getKey('cms/article_by_alias/' . $alias);
            if (!$this->_data) {
                return $this->load_by_alias($alias, true);
            }
        }
        return $this->_data;
    }

    public function auto_render_load($data) {
        if (!empty($data->related_layout)) {
            $data->related_layout = @unserialize($data->related_layout);
        }
        return $data;
    }

    // Check Exists Product By Field, Value
    public static function exists_article($field, $value, $reload = false) {
        $CI =& get_instance();
        if ($reload) {
            $query = $CI->db->get_where($CI->_instance['table'], array($field => $value), 1, 0);
            $data = $query->row();
            if (!empty($data) && intval($data->id) > 0) {
                $query->free_result();
                $CI->st_registry->setKey('cms/article_by_' . $field . '/' . $value, $data, CACHE_TIMEOUT);
                return $data;
            }
        } else {
            $data = $CI->st_registry->getKey('cms/article_by_' . $field . '/' . $value);
            if (empty($data)) {
                return $CI->exists_article($field, $value, true);
            }
        }
        return false;
    }

    public function get_data($data, $field) {
        if (is_string($data) && strstr($data, ':')) {
            $data = unserialize($data);
        }
        if (!is_array($data)) {
            return false;
        }
        if (isset($data[$field])) {
            return $data[$field];
        }
        return false;
    }

    public function delete_article($id) {
        $this->db->delete($this->_instance['table'], array('id' => $id));
        $image = $this->get_field_by_id($id, 'image');
        unlink($image);
        // Delete From Memcache
        $CI =& get_instance();
        $CI->st_registry->deleteKey('cms/article_by_id/' . $id);
        return $this;
    }

    private function auto_render($data) {
        $alias = renderToAlias($data['title']);
        if (empty($data['alias'])) {
            $data['alias'] = $alias;
        } else {
            $data['alias'] = renderToAlias($data['alias']);
        }
        if (empty($data['meta_keywords'])) {
            if (empty($data['tags'])) {
                $data['meta_keywords'] = $alias;
            } else {
                $data['meta_keywords'] = $data['tags'];
            }
        }
        if (empty($data['meta_title'])) {
            $data['meta_title'] = $data['title'];
        }
        if (empty($data['meta_description'])) {
            if (empty($data['description'])) {
                $data['meta_description'] = $data['title'];
            } else {
                $data['meta_description'] = $data['description'];
            }
        }
        if (!empty($data['category_ids'])) {
            if (is_array($data['category_ids'])) {
                $data['category_ids'] = trim(implode(',', $data['category_ids']));
            }
        }
        if (!empty($data['related_ids'])) {
            if (is_array($data['related_ids'])) {
                $data['related_ids'] = trim(implode(',', $data['related_ids']));
                if (!empty($data['related_ids'])) {
                    $query = $this->db->query('SELECT id, title, alias FROM cms_article WHERE id IN ('.$data['related_ids'].')');
                    if ($query) {
                        $result = $query->result();
                        $data['related_layout'] = serialize($result);
                    }
                    $query->free_result();
                }
            }
        }
        if (isset($data['publish_day'])) {
            if (!empty($data['publish_hour'])) {
                if (empty($data['publish_minute'])) {
                    $data['publish_minute'] = 00;
                }
                if (empty($data['publish_second'])) {
                    $data['publish_second'] = 00;
                }
                $data['publish_hour'] = render_two_digits($data['publish_hour']);
                $data['publish_minute'] = render_two_digits($data['publish_minute']);
                $data['publish_second'] = render_two_digits($data['publish_second']);
                $date = $data['publish_day'] . ' ' . $data['publish_hour'] . ':' . $data['publish_minute'] . ':' . $data['publish_second'];
                $date = strtotime(str_replace('/', '-', $date));
                $data['publish_day'] = $date;
            } else {
                $data['publish_day'] = get_time_stamp($data['publish_day']);
            }
        }
        if (empty($data['status'])) {
            $data['status'] = 0;
        }
        if (empty($data['top_home'])) {
            $data['top_home'] = 0;
        }
        if (empty($data['top_category'])) {
            $data['top_category'] = 0;
        }
        if (empty($data['hot_article'])) {
            $data['hot_article'] = 0;
        }
        $data['content'] = trim($data['content']);
        $data['words'] = str_word_count($data['content']);
        $data['updated_at'] = time();
        return $data;
    }

    public static function get_edit_url($id = null) {
        if (empty($id)) {
            return site_url('admin/cms/article/edit/', true);
        }
        return site_url('admin/cms/article/edit/id/' . $id, true);
    }

    public function get_indexes() {
        return $this->_indexes;
    }

    public function get_article_by_ids($ids, $limit) {
        if (empty($ids) || empty($limit)) {
            return null;
        }
        $query = 'SELECT id, title, alias, description, image, tags, publish_day FROM '.$this->_instance['table'].' WHERE id IN ('.$ids.') AND status = 1 ORDER BY publish_day DESC LIMIT 0, ' . $limit;
        $rs = $this->db->query($query);
        $collection = $rs->result();
        $rs->free_result();
        return $collection;
    }

    public function get_top_articles($limit = 10, $reload = true) {
        $CI = $this->get_core();
        $cache_id = 'cms/article/top/limit/' . $limit;
        $collection = $CI->st_registry->getKey($cache_id);
        if (GLOBAL_ENABLED_CACHE || $reload || empty($collection)) {
            $query = 'SELECT id, title, alias, description, image, tags, publish_day FROM '.$this->_instance['table'].' WHERE status = 1 ORDER BY publish_day DESC LIMIT 0, ' . $limit;
            $rs = $this->db->query($query);
            $collection = $rs->result();
            $rs->free_result();
            $CI->st_registry->setKey($cache_id, $collection, GLOBAL_CACHE_DURATION);
        }
        return $collection;
    }

    public function get_hot_articles($limit = 10, $reload = false) {
        $CI = $this->get_core();
        $cache_id = 'cms/article/hot/limit/' . $limit;
        $collection = $CI->st_registry->getKey($cache_id);
        if (GLOBAL_ENABLED_CACHE || $reload || empty($collection)) {
            $query = 'SELECT id, title, alias, description, image, tags, publish_day FROM '.$this->_instance['table'].' WHERE status = 1 ORDER BY hot_article DESC, hits DESC, publish_day DESC LIMIT 0, ' . $limit;
            $rs = $this->db->query($query);
            $collection = $rs->result();
            $rs->free_result();
            $CI->st_registry->setKey($cache_id, $collection, GLOBAL_CACHE_DURATION);
        }
        return $collection;
    }

    public function get_url($article = null) {
        if (empty($article)) {
            return null;
        }
        if (is_string($article)) {
            return BASE_URL . 'tin-tuc/' . $article . '.html';
        }
        if (is_object($article) && isset($article->alias) && isset($article->id)) {
            return BASE_URL . 'tin-tuc/' . $article->alias . '-a' . $article->id . '.html';
        }
        if (is_array($article) && isset($article['alias']) && isset($article['id'])) {
            return BASE_URL . 'tin-tuc/' . $article['alias'] . '-a' . $article['id'] . '.html';
        }
        return null;
    }

    public function get_same_category_articles($cat_ids, $eid = 0, $limit = 8) {
        $query = 'SELECT id, title, alias, description, image, tags, publish_day FROM '.$this->_instance['table'].' WHERE status = 1 AND category_ids IN (' . $cat_ids . ') AND id <> '.$eid.' ORDER BY publish_day DESC LIMIT 0, ' . $limit;
        $rs = $this->db->query($query);
        $collection = $rs->result();
        $rs->free_result();
        return $collection;
    }

    public function get_list_status() {
        return $this->_status;
    }

    public function get_status_label($status) {
        $list = $this->get_list_status();
        if (!isset($list[$status])) {
            return $list[0];
        }
        return $list[$status];
    }

    public function get_list_types() {
        $list = array();
        $list[cms_article_model::TYPE_NORMAL] = 'Kiểu tin';
        $list[cms_article_model::TYPE_IMAGE] = 'Kiểu ảnh';
        $list[cms_article_model::TYPE_VIDEO] = 'Kiểu video';
        $list[cms_article_model::TYPE_MIXED] = 'Kiểu tổng hợp';
        return $list;
    }

    public function get_type_label($type) {
        $list = $this->get_list_types();
        if (!isset($list[$type])) {
            return $list[cms_article_model::TYPE_NORMAL];
        }
        return $list[$type];
    }

    public function get_status($id) {
        $query = 'SELECT `status` FROM '.$this->_instance['table'].' WHERE id = '.$id.' LIMIT 0, 1';
        $rs = $this->db->query($query);
        $row = $rs->row();
        $rs->free_result();
        return $row->status;
    }

    public function update_status($id, $status, $note = '') {
        $admin = new admin_model();
        $user_id = $admin->get_id();
        $updated_at = time();
        $data = array('status' => $status, 'last_editor_id' => $user_id, 'updated_at' => $updated_at);
        // Update Status
        $this->db->where('id', $id);
        $this->db->update($this->_instance['table'], $data);
        return $this;
    }

    public function parse_alias($alias) {
        $alias = trim($alias);
        if (!is_string($alias)) {
            return null;
        }
        $data = array('alias' => $alias);
        switch ($alias) {
            case 'deleted':
            case 'delete':
                $data['label'] = 'Xóa';
                break;
            case 'publish':
                $data['status'] = 1;
                $data['label'] = 'Xuất bản';
                break;
            case 'unpublish':
                $data['status'] = 2;
                $data['label'] = 'Gỡ bỏ';
                break;
        }
        return $data;
    }

    public function get_all_status() {
        return $this->_status;
    }
}

?>